package org.belkodevelop.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.belkodevelop.controller.helper.AuthUtils;
import org.belkodevelop.role.RoleConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Controller
@RequestMapping("/login.do")
public class AuthController {

    private final Log log = LogFactory.getLog(getClass()); 
    
    @Autowired
    private AuthUtils authUtils;

    @RequestMapping(method = RequestMethod.GET)
    public String toJsp() {
        return "login";
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView login(@RequestParam("login") String login,
                            @RequestParam("password") String password,
                            @RequestParam(value = "rememberMe", required = false) String rememberMe,
                            HttpServletRequest request, 
                            HttpServletResponse response) throws IOException {
        boolean rememberMeFlag = rememberMe != null && !rememberMe.equals("") ? true : false;
        try {

            if (StringUtils.isEmpty(login) || StringUtils.isEmpty(password)) {
                return new ModelAndView("login", "errorMessage", "error.login.please_enter");
            }
            boolean result = authUtils.login(login.trim().toLowerCase(), password.trim(), rememberMeFlag, request, response);
            if (!result) {
                return new ModelAndView("login", "errorMessage", "error.login");
            }
            if (authUtils.getCurrentSessionUser().getRoles().contains(RoleConstants.PATIENT_ROLE)) {
                return new ModelAndView("redirect:/cabinet/");
            } else if (authUtils.getCurrentSessionUser().getRoles().contains(RoleConstants.DOCTOR_ROLE)) {
                return new ModelAndView("redirect:/doctor/");
            } else if (authUtils.getCurrentSessionUser().getRoles().contains(RoleConstants.ADMIN_ROLE)) {
                return new ModelAndView("redirect:/admin/");
            } else {
                response.sendError(404);
                return null;
            }

        } catch (AuthenticationException e) {
            log.warn("Error login user", e);
            return new ModelAndView("login", "errorMessage", "error.login");
        }
    }
}